<template>
  <div>
    <el-dialog title="绑定设备" :visible.sync="dialogVisible" width="480px" :before-close="closeDialog"
      :close-on-click-modal="false">
      <el-form :model="addForm" :rules="rules" ref="refForm" label-width="95px">
        <el-form-item size="small" label="组织机构" prop="parentId"
          v-if="user.roleName === 'TENANT_ADMIN' || user.roleName === 'ORG_ADMIN'">
          <TreeSearchAdd style="width: 320px" @changeOrgId="changeOrgId" @onClear="onClear" ref="refTreeSearchAdd">
          </TreeSearchAdd>
        </el-form-item>
        <el-form-item size="small" label="联网单位" prop="orgId">
          <el-select size="small" style="width: 320px;" clearable v-model='addForm.orgId'
            placeholder='请选择' filterable  @clear="handleClear"
            @change="changeunitId">
            <el-option v-for='item in orgList' :label='item.orgName' :value='item.id' :key='item.id'>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="建筑" prop="buildId">
          <el-select v-model="addForm.buildId" filterable placeholder="请选择" style="width: 320px" @change="changeBuild"
            v-loadMore="loadMore">
            <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
            <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="楼层" prop="floorId">
          <el-select v-model="addForm.floorId" filterable placeholder="请选择" style="width: 320px" @change="changeFloor"
            v-loadMore="loadMore2">
            <el-option v-for="item in floorList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
            <div class="div_box" v-loading="loading2" :style="loading2 ? '' : 'display: none;'"></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="安装点" prop="spaceId">
          <el-select v-model="addForm.spaceId" placeholder="请选择" style="width: 320px" filterable v-loadMore="loadMore3">
            <el-option v-for="item in spaceList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
            <div class="div_box" v-loading="loading3" :style="loading3 ? '' : 'display: none;'"></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="设备编码" prop="imei">
          <el-input style="width: 320px" oninput="value=value.replace(/[\u4e00-\u9fa5]/g,'')"
            @blur="addForm.imei = $event.target.value" clearable v-model="addForm.imei" placeholder="请输入"
            maxlength="25"></el-input>
        </el-form-item>

        <el-form-item size="small" label="位置标记">
          <div style="display: flex; align-items: center">
            <!-- <el-input style="width: 320px" clearable v-model="addForm.n" placeholder="" maxlength="20" disabled></el-input> -->
            <el-button size="small" type="primary" @click="sign" icon="el-icon-location-outline">{{ nameMark
            }}</el-button>
          </div>
        </el-form-item>

        <!-- <el-form-item size="small" label="安装人手机" prop="mobile">
          <el-input
            clearable
            v-model="addForm.mobile"
            placeholder="请输入安装人员手机号"
            oninput="value=value.replace(/\s*/g,'')"
            @blur="addForm.mobile = $event.target.value"
            maxlength="11"
          ></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" @click="submit" v-preventReClick="1000" class="confirm-button">确 定</el-button>
      </span>
    </el-dialog>

    <Ichnography ref="refIchnography" @clickMark="clickMark"></Ichnography>
  </div>
</template>

<script>
import { reqDeviceBind, reqSpaceManager, reqFloorById, reqOrgList } from "@api/api.js";
import { validateImei } from "@utils/validate";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import Ichnography from "../components/Ichnography.vue";
import TreeSearchAdd from "@components/TreeSearchAdd.vue";

export default {
  props: [],
  mixins: [loadMore],
  components: {
    Ichnography,
    TreeSearchAdd,
  },
  data() {
    return {
      dialogVisible: false,
      buildList: [],
      floorList: [],
      spaceList: [],
      addForm: {
        imei: "",
        buildId: "",
        floorId: "",
        spaceId: "",
        targetId: "",
        parentId: "",
        orgId:"",
      },
      rules: {
        orgId: [
          { required: true, message: "请选择联网单位", trigger: "change" },
        ],
        parentId: [
          { required: true, message: "请选择组织机构", trigger: "change" },
        ],
        imei: [
          { required: true, message: "请输入设备编码", trigger: "blur" },
          { validator: validateImei },
        ],
        buildId: [
          { required: true, message: "请选择建筑物", trigger: "change" },
        ],
        floorId: [{ required: true, message: "请选择楼层", trigger: "change" }],
        spaceId: [
          { required: true, message: "请选择安装点", trigger: "change" },
        ],
      },
      loading: false,
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,
      sysInstanceIndex3: 1,
      sysInstanceTotalPages3: 10,
      loading3: false,
      nameMark: "标记",
      mark: "",
      orgList: [],
      unitIndex: 1,
      unitPages: 10,
      unitloading: false,
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    dialogVisible(e) {
      if (e) {
        this.$nextTick(() => {
          if (this.$refs.refTreeSearchAdd) {
            this.$refs.refTreeSearchAdd.getDataList();
          }
        });
      }
    },
  },
  methods: {
    changeunitId(e) {
      this.buildList = this.floorList = this.spaceList = [];
      this.addForm.buildId = this.addForm.floorId = this.addForm.spaceId = "";
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      if (e != '') {
        this.getBuildList();
      }
    },
    // 清空
    handleClear() {
      this.orgName = '';
      this.unitIndex = 1;
      this.unitPages = 10;
      this.orgList = []
      this.getOrgList()

      this.addForm.orgId = "";
      this.buildList = this.floorList = this.spaceList = [];
      this.addForm.buildId = this.addForm.floorId = this.addForm.spaceId = "";
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
    },
    // 远程搜索
    async remoteMethod(query) {
      this.addForm.orgId = query //保留输入的值
      this.orgName = query;
      this.unitIndex = 1;
      this.unitPages = 10;
      this.orgList = []
      this.getOrgList()
    },
    async unitMore() {
      if (this.unitIndex >= Math.ceil(this.unitPages / 10)) return
      this.unitIndex++
      this.unitloading = true;
      // 获取列表数据的方法
      await this.getOrgList()
      this.unitloading = false;
    },
    // 请求单位列表
    async getOrgList() {
      let { tenantId, userId, roleName } = this.user;
      const res = await reqOrgList({
        tenantId,
        userId,
        roleName,
        orgName: this.orgName,
        parentId: this.addForm.parentId,
        type: "4"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.orgList = res.data.rows
    },

    changeOrgId(instanceId) {
      // this.sysInstanceIndex = 1;
      // this.addForm.buildId = "";
      // this.buildList = [];
      // this.getBuildList();
      this.addForm.parentId = instanceId.id
      this.handleClear();
    },
    onClear() {
      // this.addForm.targetId = this.spacesManage.organizationInfo.orgId;
      // this.sysInstanceIndex = 1;
      // this.addForm.buildId = "";
      // this.buildList = [];
      // this.getBuildList();

      this.addForm.parentId = ''
      this.handleClear();
    },
    async sign() {
      if (this.addForm.spaceId == "")
        return this.$modal.notifyWarning("请先选择安装点!");
      const res = await reqFloorById(this.addForm.spaceId);
      // console.log(res);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      if (res.data.rows.image == "")
        return this.$modal.notifyWarning("当前楼层暂无平面图,请上传后操作!");
      this.$refs.refIchnography.dialogVisible = true;
      this.$refs.refIchnography.getimage(res.data.rows.image);
      if (this.nameMark == "已标记") {
        this.$refs.refIchnography.getMark(this.mark);
      }
    },
    // 子组件事件
    clickMark(e) {
      // console.log(e);
      this.mark = e;
      this.nameMark = "已标记";
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.getBuildList();
      this.loading = false;
    },
    // 获取建筑物列表
    async getBuildList() {
      let res = await reqSpaceManager(this.sysInstanceIndex, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.addForm.orgId,
        metaCode: 1,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages = res.data.total;
      this.buildList = [...this.buildList, ...res.data.rows];
    },
    // 选择建筑物
    changeBuild() {
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.getFloorList();
      this.floorList = this.spaceList = [];
      this.addForm.floorId = this.addForm.spaceId = "";
    },

    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.getFloorList();
      this.loading2 = false;
    },
    // 获取楼层列表
    async getFloorList() {
      let res = await reqSpaceManager(this.sysInstanceIndex2, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.addForm.orgId,
        parentId: this.addForm.buildId,
        metaCode: 2,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total;
      this.floorList = [...this.floorList, ...res.data.rows];
    },
    // 选择楼层
    changeFloor() {
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.getSpaceList();
      this.spaceList = [];
      this.addForm.spaceId = "";

      this.mark = "";
      this.nameMark = "标记";
    },

    async loadMore3() {
      if (this.sysInstanceIndex3 >= Math.ceil(this.sysInstanceTotalPages3 / 10))
        return;
      this.sysInstanceIndex3++;
      this.loading3 = true;
      // 获取列表数据的方法
      await this.getSpaceList();
      this.loading3 = false;
    },
    // 获取安装点列表
    async getSpaceList() {
      let res = await reqSpaceManager(this.sysInstanceIndex3, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.addForm.orgId,
        parentId: this.addForm.floorId,
        metaCode: 3,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages3 = res.data.total;
      this.spaceList = [...this.spaceList, ...res.data.rows];
    },
    // 点击绑定
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        if (!valid) return;
        let { imei, spaceId } = this.addForm;
        const res = await reqDeviceBind({
          imei,
          spaceId,
          userId: this.user.userId,
          mark: this.mark,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("绑定成功");
        this.closeDialog();
        this.$refs.refIchnography.closeDialog();
        this.$parent.getDataList();
      });
    },
    // 点击关闭弹框
    closeDialog() {
      this.$refs.refIchnography.closeDialog();
      this.$refs.refForm.resetFields();
      this.buildList = [];
      this.floorList = [];
      this.spaceList = [];
      this.addForm.parentId = "";
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.nameMark = "标记";
      this.mark = "";
      this.dialogVisible = false;
      if (this.$refs.refTreeSearchAdd) {
        this.$refs.refTreeSearchAdd.onclose();
      }
    },
  },
  deactivated() {
    if (this.$refs.refIchnography != null || this.$refs.refForm != null) {
      this.closeDialog();
    }
  },
};
</script>

<style lang="less" scoped>
// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 2016;
  // background: red;
  // opacity: 0.5;
}

// 下拉框加载结束

::v-deep .el-loading-mask {
  border-radius: 4px;
}
</style>
